<?php

/**
 * 注消所有全局变量.
 *
 * @return null 将返回null，如果register_globals的PHP指令被禁用
 */
function cb_unregister_GLOBALS() {
    if (!ini_get('register_globals'))
        return;

    if (isset($_REQUEST ['GLOBALS']))
        die('GLOBALS overwrite attempt detected');

    $noUnset = array('GLOBALS', '_GET', '_POST', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');

    $input = array_merge($_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_FILES, isset($_SESSION) && is_array($_SESSION) ? $_SESSION : array());
    foreach ($input as $k => $v)
        if (!in_array($k, $noUnset) && isset($GLOBALS [$k])) {
            $GLOBALS [$k] = NULL;
            unset($GLOBALS [$k]);
        }
}

/**
 * 修正PHP的运行环境
 *
 * @return null
 */
function cb_fix_PHP_ENV() {

    global $PHP_SELF;

    $default_server_values = array('SERVER_SOFTWARE' => '', 'REQUEST_URI' => '');

    $_SERVER = array_merge($default_server_values, $_SERVER);

    // Fix for IIS when running with PHP ISAPI
    if (empty($_SERVER ['REQUEST_URI']) || (php_sapi_name () != 'cgi-fcgi' && preg_match('/^Microsoft-IIS\//', $_SERVER ['SERVER_SOFTWARE']))) {

        // IIS Mod-Rewrite
        if (isset($_SERVER ['HTTP_X_ORIGINAL_URL'])) {
            $_SERVER ['REQUEST_URI'] = $_SERVER ['HTTP_X_ORIGINAL_URL'];
        } // IIS Isapi_Rewrite
        else if (isset($_SERVER ['HTTP_X_REWRITE_URL'])) {
            $_SERVER ['REQUEST_URI'] = $_SERVER ['HTTP_X_REWRITE_URL'];
        } else {
            // Use ORIG_PATH_INFO if there is no PATH_INFO
            if (!isset($_SERVER ['PATH_INFO']) && isset($_SERVER ['ORIG_PATH_INFO']))
                $_SERVER ['PATH_INFO'] = $_SERVER ['ORIG_PATH_INFO'];

            // Some IIS + PHP configurations puts the script-name in the path-info (No need to append it twice)
            if (isset($_SERVER ['PATH_INFO'])) {
                if ($_SERVER ['PATH_INFO'] == $_SERVER ['SCRIPT_NAME'])
                    $_SERVER ['REQUEST_URI'] = $_SERVER ['PATH_INFO'];
                else
                    $_SERVER ['REQUEST_URI'] = $_SERVER ['SCRIPT_NAME'] . $_SERVER ['PATH_INFO'];
            }

            // Append the query string if it exists and isn't null
            if (!empty($_SERVER ['QUERY_STRING'])) {
                $_SERVER ['REQUEST_URI'] .= '?' . $_SERVER ['QUERY_STRING'];
            }
        }
    }

    // Fix for PHP as CGI hosts that set SCRIPT_FILENAME to something ending in php.cgi for all requests
    if (isset($_SERVER ['SCRIPT_FILENAME']) && (strpos($_SERVER ['SCRIPT_FILENAME'], 'php.cgi') == strlen($_SERVER ['SCRIPT_FILENAME']) - 7))
        $_SERVER ['SCRIPT_FILENAME'] = $_SERVER ['PATH_TRANSLATED'];

    // Fix for Dreamhost and other PHP as CGI hosts
    if (strpos($_SERVER ['SCRIPT_NAME'], 'php.cgi') !== false)
        unset($_SERVER ['PATH_INFO']);

    // Fix empty PHP_SELF
    $PHP_SELF = $_SERVER ['PHP_SELF'];
    if (empty($PHP_SELF))
        $_SERVER ['PHP_SELF'] = $PHP_SELF = preg_replace('/(\?.*)?$/', '', $_SERVER ["REQUEST_URI"]);
}

function cb_check_php_mysql_versions() {
    require_once CB_CORE . 'version.php';
    if (version_compare(REQUIRED_PHP_VERSION, PHP_VERSION, '>'))
        die(sprintf('您的服务器当前运行的PHP版本为： %s .城市宝系统所需要的最低版本为：' . REQUIRED_PHP_VERSION . '.', PHP_VERSION));

    if (!extension_loaded('mysql') && !file_exists(CB_INCLUDE . '/db.class.php'))
        die('运行城市宝系统需要MySql扩展，但在您的服务器上，PHP没有开启MySql扩展.');
}

function cb_check_maintenance() {
    global $config_core;
    if (!$config_core) {
        cb_init_config_core();
    }
    if ($config_core ['site_state'] || defined('CB_INSTALLING'))
        return;

    $protocol = $_SERVER ["SERVER_PROTOCOL"];
    if ('HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol)
        $protocol = 'HTTP/1.0';
    header("$protocol 503 Service Unavailable", true, 503);
    header('Content-Type: text/html; charset=utf-8');
    header('Retry-After: 600');
?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>系统维护中……</title>
        </head>
        <body>
            <h1><?php echo $config_core ['site_close_reason'] ?></h1>
        </body>
    </html>
<?php
    die ();
}

function cb_magic_quotes() {
    if (get_magic_quotes_gpc ()) {
        $_GET = stripslashes_deep($_GET);
        $_POST = stripslashes_deep($_POST);
        $_COOKIE = stripslashes_deep($_COOKIE);
    }

    $_GET = add_magic_quotes($_GET);
    $_POST = add_magic_quotes($_POST);
    $_COOKIE = add_magic_quotes($_COOKIE);
    $_SERVER = add_magic_quotes($_SERVER);

    $_REQUEST = array_merge($_GET, $_POST);
}

function cb_init_db() {
    global $cbdb;
    if (!is_object($cbdb) || !is_a($cbdb, 'cbdb')) {
        if (file_exists(CB_INCLUDE . 'db.class.php'))
            require_once CB_INCLUDE . 'db.class.php';
        else
            require_once (CB_ROOT . 'db.class.php');
        $cbdb = new cbdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
    }
    return $cbdb;
}

function cb_init_config_core() {
    global $cbdb, $config_core;
    if (!$cbdb) {
        cb_init_db();
    }
    if (!$config_core) {
        //加载配置
        $config_core = cb_cache_get('core', 'settings');
    }
    return $config_core;
}

function cb_init_template() {
    global $tpl, $config_core;
    if (!$config_core) {
        cb_init_config_core();
    }
    if (!is_object($tpl) || !is_a($tpl, 'Smarty')) {
        require_once CB_LIBRARY . 'smarty/Smarty.class.php';
        $tpl = new Smarty ();
    }
    if (defined('CB_ADMIN')) {
        $template_dir = CB_ROOT . 'admin/templates';
    } else {
        $template_dir = CB_ROOT . 'templates/' . $config_core ['current_template'];
    }
    $tpl->template_dir = $template_dir;
    $tpl->compile_dir = CB_DATA . 'templates_compile';
    $tpl->compile_id = $template_dir;
    if (!defined('CB_ADMIN') && defined("APPLICATION_ENV") && APPLICATION_ENV == 'product') {
        $tpl->compile_check = false;
    }
    if (!is_dir(CB_DATA . 'cache/pages') && !mkdir(CB_DATA . 'cache/pages')) {
        die('页面缓存目录创建失败！请检查目录权限！');
    }
    $tpl->cache_dir = CB_DATA . 'cache/pages';
    if (!defined('CB_ADMIN')) {
        $tpl->caching = $config_core ['page_cache_time'] ? 1 : 0;
        $tpl->cache_lifetime = $config_core ['page_cache_time'];
    }
    $tpl->left_delimiter = '<!--{';
    $tpl->right_delimiter = '}-->';
    $tpl->assign('SITE_NAME', $config_core ['site_name']);
    $tpl->assign('SITE_URL', $config_core ['site_url']);
    if (!defined('CSS_DIR'))
        define('CSS_DIR', INSTALL_PATH . str_replace(CB_ROOT, '', $template_dir) . '/css/');
    $tpl->assign('CSS_DIR', CSS_DIR);
    if (!defined('IMG_DIR'))
        define('IMG_DIR', INSTALL_PATH . str_replace(CB_ROOT, '', $template_dir) . '/images/');
    $tpl->assign('IMG_DIR', IMG_DIR);
    if (!defined('JS_DIR'))
        define('JS_DIR', INSTALL_PATH . 'javascript/');
    $tpl->assign('JS_DIR', JS_DIR);
    $tpl->assign('CB_DOMAIN', $config_core ['site_domain']);
    $tpl->assign('SAFE_DOMAIN', $config_core ['safe_domain']);
    $tpl->assign('INSTALL_PATH', INSTALL_PATH);
    $tpl->assign('CHARSET', CHARSET);
    $tpl->assign('config_core', $config_core);
    unset($template_dir);
    return $tpl;
}

function cb_init_session() {
    global $cbdb;
    if (!$cbdb) {
        cb_init_db();
    }
    require_once CB_INCLUDE . 'session.func.php';
    session_set_save_handler("mysql_session_open", "mysql_session_close", "mysql_session_read", "mysql_session_write", "mysql_session_destroy", "mysql_session_garbage_collect");
    session_start ();
}

function favicon_request() {
    if ('/favicon.ico' == $_SERVER ['REQUEST_URI']) {
        header('Content-Type: image/vnd.microsoft.icon');
        header('Content-Length: 0');
        exit ();
    }
}

function cb_init_user() {
    require_once CB_INCLUDE . 'user.func.php';
    global $user, $cbdb, $group_power, $tpl, $config_member;
    if (!$cbdb) {
        cb_init_db();
    }
    if (!$tpl) {
        cb_init_template();
    }
    $user = new stdClass ();
    $user->userid = 0;
    $user->username = '';
    $user->groupid = 5; //5游客
    $uesr->truename = '';
    $local_user = get_cookie('auth_user');
    if ($local_user) {
        if ($local_user->userid) {
            $db_user = $cbdb->get_row('SELECT * FROM {#cbdbPrefix}members WHERE userid=' . $local_user->userid . ' LIMIT 0,1');
            if ($db_user && $db_user->password == $local_user->password) {
                if ($db_user->groupid == 6) { //6禁止访问
                    show_message('您的用户级别为禁止访问!');
                }
                if ($db_user->keep_loginip && $db_user->keep_loginip != IP_ADDRESS) {
                    set_cookie('auth_user', '');
                    show_message("您的帐号限制了登录IP（" . $db_user->keep_loginip . "），您当前的IP（" . IP_ADDRESS . "）不允许登录系统！<br />我们已将您的帐号下线，请您更换帐号登录，或与管理员联系。", INSTALL_PATH);
                }
                if ($db_user->last_loginip != IP_ADDRESS) {
                    set_cookie('auth_user', '');
                    show_message('您的帐号在别处(IP:' . $db_user->last_loginip . ')登录，您被迫下线<br />如果不是您操作的，请尽快修改登录密码', INSTALL_PATH);
                }
                $user = $db_user;
            }
        }
    }

    $group_power = cb_cache_get('group_' . $user->groupid, 'power');
    if (!isset($config_member)) {
        $config_member = cb_cache_get('member', 'settings');
    }
    if (isset($config_member['ifonline_user']) && $config_member['ifonline_user']) {
        write_online_user();
    }
    if ($user->userid <= 0 && defined('NEED_LOGIN') && NEED_LOGIN) {
        redirect(INSTALL_PATH . 'member/login.php');
    }
    $tpl->assign('user', $user);
    return $user;
}

function cb_init_logger() {
    global $logger, $cbdb;
    if (!$cbdb) {
        cb_init_db();
    }
    if (!is_object($logger) || !is_a($logger, 'logger')) {
        require_once CB_INCLUDE . 'log.class.php';
        $logger = new logger($cbdb, 'logs');
    }
    return $logger;
}

function cb_init_uploader() {
    global $uploader, $config_core;
    if (!$config_core) {
        cb_init_config_core();
    }
    if (!is_object($uploader) || !is_a($uploader, 'cb_upload')) {
        require_once CB_INCLUDE . 'upload.class.php';
        $uploader = new cb_upload();
    }
    $uploader->out_file_dir = CB_ROOT . $config_core['upload_path'];
    $uploader->max_file_size = intval($config_core['max_file_size']) * 1048576;
    $uploader->make_script_safe = $config_core['make_script_safe'];
    $uploader->allowed_file_ext = explode('|', $config_core['allowed_file_ext']);
    return $uploader;
}

function cb_init_image_handler() {
    global $image_handler, $config_core;
    if (!$config_core) {
        cb_init_config_core();
    }
    if (!is_object($image_handler) || !is_a($image_handler, 'cb_image')) {
        require_once CB_INCLUDE . 'image.class.php';
        $image_handler = new cb_image();
    }
    $image_handler->out_file_dir = CB_ROOT . $config_core['upload_path'];
    $image_handler->max_file_size = intval($config_core['max_file_size']) * 1048576;
    $image_handler->make_script_safe = $config_core['make_script_safe'];
    $image_handler->allowed_file_ext = explode('|', $config_core['allowed_file_ext']);
    $image_handler->mask_type = $config_core['water_type'];
    $image_handler->mask_minwidth = $config_core['water_minwidth'];
    $image_handler->mask_minheight = $config_core['water_minheight'];
    $image_handler->mask_position = $config_core['water_pos'];
    $image_handler->mask_img = CB_ROOT . $config_core['water_image'];
    $image_handler->mask_img_pct = $config_core['water_transition'];
    $image_handler->water_jpeg_quality = $config_core['water_jpeg_quality'];
    $image_handler->mask_word = $config_core['water_text'];
    $image_handler->font = CB_DATA . 'fonts/' . $config_core['water_font'];
    $image_handler->font_size = $config_core['water_fontsize'];
    $image_handler->mask_font_color = $config_core['water_fontcolor'];
    return $image_handler;
}
